import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,asyncRoutes,anyRoutes,constantRoutes } from '@/router'
import router from '@/router'

const getDefaultState = () => {
    return {
        token: getToken(),
        name: '',
        avatar: '',
        routes:[],
        role:[],
        buttons:[],
        // 对比之后[项目中也有的异步路由,与服务器返回的标记相信进行对比,最终需要展示的路由]
        resultAsyncRoutes:[],
        // 用户最终需要展示的全部路由
        resultAllRoutes: []
    }
};

const state = getDefaultState();

const mutations = {
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    // 存储用户信息
    SET_USERINFO: (state,userInfo) => {
        state.name = userInfo.name;
        state.avatar = userInfo.avatar;
        // 菜单权限的标记
        state.routes = userInfo.routes;
        // 按钮权限的标记
        state.buttons = userInfo.buttons;
        // 角色
        state.roles = userInfo.roles;
    },

    // 最终计算出来的异步路由
    SET_RESULTASYNCROUTES:(state,asyncRoutes) => {
        // vuex保存当前用户的异步路由
        state.resultAsyncRoutes = asyncRoutes;
        state.resultAllRoutes = constantRoutes.concat(state.resultAsyncRoutes,anyRoutes);
        router.addRoutes(state.resultAllRoutes);
    },


};

const actions = {
    // user login
    async login({ commit }, userInfo) {
        let {username,password} = userInfo;
        let result = await login({ username: username.trim(), password: password });
        console.log(result);
        if(result.code === 20000) {
            let data = result.data;
            setToken(data.token);
            commit('SET_TOKEN', data.token);
            return 'OK';
        }else {
            return Promise.reject(new Error('failed'))
        }
    },

    // get user info
    getInfo({ commit, state }) {
        return new Promise((resolve, reject) => {
            getInfo(state.token).then(response => {
                // 获取用户信息:返回的数据包含:用户名name,用户头像avatar,routes[返回的标志:不同的用户应该展示那些菜单的标记]
                const { data } = response;

                // vuex存储用户全部信息
                commit('SET_USERINFO',data);
                console.log(data);
                commit('SET_RESULTASYNCROUTES',computedAsyncRoutes(asyncRoutes,data.routes));
                resolve(data)
            }).catch(error => {
                reject(error);
            })
        })
    },

    // user logout
    logout({ commit, state }) {
        return new Promise((resolve, reject) => {
            logout(state.token).then(() => {
                removeToken(); // must remove  token  first
                resetRouter();
                commit('RESET_STATE');
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // remove token
    resetToken({ commit }) {
        return new Promise(resolve => {
            removeToken(); // must remove  token  first
            commit('RESET_STATE');
            resolve()
        })
    }
};

// 两个数组进行对比,对比出当前用户到底显示那些异步路由
const computedAsyncRoutes = (asyncRoutes,routes) => {
    return  asyncRoutes.filter((item) => {
        if(routes.indexOf(item.name)!==-1) {
            if(item.children&&item.children.length) {
                item.children = computedAsyncRoutes(item.children,routes);
            }
            return true;
        }
    })
};

export default {
    namespaced: true,
    state,
    mutations,
    actions
}

